<template>
    <div>
        <div class="container">
            <div class="form-box">
                <el-form ref="form" :model="form" label-width="70px">
                    <el-form-item label="分销商：" prop="teahouseId">
                        <el-select v-model="form.teahouseId" @change="handleBrandChange" placeholder="请选择分销商">
                            <el-option v-for="item in brandOptions" :key="item.value" :label="item.label"
                                       :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="商品分类：" prop="productCategoryId">
                        <el-cascader v-model="selectProductCateValue" :options="productCateOptions">
                        </el-cascader>
                    </el-form-item>
                    <el-form-item label="商品标题">
                        <el-input v-model="form.title" placeholder="请输入产品名称"></el-input>
                    </el-form-item>
                    <el-form-item label="副标题">
                        <el-input v-model="form.subTitle" placeholder="请输入产品名称"></el-input>
                    </el-form-item>
                    <el-form-item label="标签">
                        <el-input v-model="form.label" placeholder="请输入产品标签，多标签之间用‘,’隔开，如 '多汁,美味' "></el-input>
                    </el-form-item>
                    <el-form-item label="视频地址">
                        <el-input v-model="form.videoUrl" placeholder="请输入视频地址"></el-input>
                    </el-form-item>
                    <el-form-item label="备注">
                        <el-input v-model="form.remark" placeholder="请输入备注"></el-input>
                    </el-form-item>
                    <el-form-item label="展示图">
                        <el-upload
                                class="avatar-uploader"
                                :headers="myHeaders"
                                :action="uploadsrc"
                                accept="image/jpeg,image/gif,image/png"
                                list-type="picture-card"
                                :limit="1"
                                :before-upload="handleBeforeUpload"
                                :on-success="uploadLogoSuccess"
                                :on-error="uploadError"
                                :data="pdfData"
                                :file-list="logolist"
                        >
                            <img v-if="imageUrl" :src="imageUrl" class="avatar" v-model="form.listLogo">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="轮播图">
                        <el-upload
                                class="avatar-uploader"
                                :headers="myHeaders"
                                :action="uploadsrc"
                                accept="image/jpeg,image/gif,image/png"
                                list-type="picture-card"
                                :limit="6"
                                :before-upload="handleBeforeUpload"
                                :on-success="uploadSuccess"
                                :on-error="uploadError"
                                :on-remove="handleRemove"
                                :data="pdfData"
                                :file-list="imglist"
                        >
                            <img v-if="imageUrl" :src="imageUrl" class="avatar" v-model="form.detailBanner">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="商品介绍">
                        <quill-editor ref="myTextEditor" v-model="form.introduce" @change="introduceHtml">
                        </quill-editor>
                    </el-form-item>
                    <el-form-item label-width="255px">
                        <el-button type="primary" @click="onSubmit(form)">点击添加商品</el-button>
                        <el-button @click="cancel">取消</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script>
    import 'quill/dist/quill.core.css';
    import 'quill/dist/quill.snow.css';
    import 'quill/dist/quill.bubble.css';
    import { uploadsrc } from '../../../utils/dcf2d0812e764796a97bb2e8c1725fab.js';
    import { dynamicHeader } from '../../../utils/dcf2d0812e764796a97bb2e8c1725fab.js';

    export default {
        name: 'addVoucher',
        data() {
            return {
                selectProductCateValue: [],
                productCateOptions: [],
                productCategoryId: [{ required: true, message: '请选择商品分类', trigger: 'blur' }],
                parentId: 0,
                parentid: 0,
                parentids: [],
                deliverType: [
                    { id: 1, name: '正常发货' },
                    { id: 2, name: '延迟天数发货' },
                    { id: 3, name: '具体发货时间' }
                ],
                categoryIds: [],
                imageUrl: '',
                category: null,
                imglist: [],
                index: '',
                distributorIds: [],
                ortool: true,
                goodsTypes: [{
                    type: 1,
                    name: '普通商品'
                }, {
                    type: 2,
                    name: '套餐商品'
                }],
                logolist: [],
                pdfData: {
                    type: 1,
                    path: 1
                },
                submit: {
                    detailBanner: ''
                },
                myHeaders: {},
                form: {
                    detailBanner: ''
                },
                windowName: '',
                brandOptions: [],
                brandId: [{ required: true, message: '请选择商品品牌', trigger: 'blur' }]
                // secondID:''
            };
        },
        created() {
            this.getDistributorList();
            this.uploadsrc = uploadsrc;
            //注意：parent 是 JS 自带的全局对象，可用于操作父页面
            this.windowName = parent.layer.getFrameIndex(window.name); //获取窗口索引
        },
        watch: {
            selectProductCateValue: function(newValue) {
                if (newValue != null && newValue.length === 2) {
                    this.form.categoryId = newValue[1];
                    this.form.categoryName = this.getCateNameById(this.form.categoryId);
                } else {
                    this.form.categoryId = null;
                    this.form.categoryName = null;
                }
            }
        },
        methods: {
            introduceHtml({ editor, html, text }) {
                this.form.introduce = html;
            },
            productFeaturesHtml({ editor, html, text }) {
                this.form.productFeatures = html;
            },
            afterSaleServiceHtml({ editor, html, text }) {
                this.form.afterSaleService = html;
            },
            getDistributorList() {
                teahouseList({ pageNum: 1, pageSize: 100, param: {} }).then(res => {
                    this.brandOptions = [];
                    let distributorList = res.data.list;
                    for (let i = 0; i < distributorList.length; i++) {
                        this.brandOptions.push({ label: distributorList[i].name, value: distributorList[i].id });
                    }
                });
            },
            handleBrandChange(val) {
                let brandName = '';
                let id = null;
                for (let i = 0; i < this.brandOptions.length; i++) {
                    if (this.brandOptions[i].value === val) {
                        brandName = this.brandOptions[i].label;
                        id = this.brandOptions[i].value;
                        break;
                    }
                }
                this.form.brandName = brandName;
                this.getProductCateList();
            },
            onSubmit(row) {
                this.submit = row;
                var detailBanner = row.detailBanner.length > 1 ? row.detailBanner.join(',') : row.detailBanner[0];
                this.submit.detailBanner = detailBanner;
                addGoods(this.submit).then(res => {
                    console.log(res);
                    if (res.returnCode == 200) {
                        layer.alert('下一步添加价格', function() {
                            layer.close(layer.index);
                            this.form = null;
                            location.href = '/#/goodsPriceAdd?goodsId=' + res.data;
                        });
                    } else {
                        layer.alert(res.returnMsg, {
                            icon: 2,
                            skin: 'layer-ext-moon'
                        });
                    }
                });
            },
            //处理编辑逻辑
            handleEditCreated() {
                if (this.form.categoryId != null) {
                    this.selectProductCateValue.push(this.form.categoryId);
                    this.selectProductCateValue.push(this.form.categoryId);
                }
                this.hasEditCreated = true;
            },
            getProductCateList() {
                listWithChildren().then(res => {
                    let list = res.data;
                    this.productCateOptions = [];
                    for (let i = 0; i < list.length; i++) {
                        let children = [];
                        if (list[i].children != null && list[i].children.length > 0) {
                            for (let j = 0; j < list[i].children.length; j++) {
                                children.push({ label: list[i].children[j].name, value: list[i].children[j].id });
                            }
                        }
                        this.productCateOptions.push({ label: list[i].name, value: list[i].id, children: children });
                    }
                });
            },
            getCateNameById(id) {
                let name = null;
                for (let i = 0; i < this.productCateOptions.length; i++) {
                    for (let j = 0; j < this.productCateOptions[i].children.length; j++) {
                        if (this.productCateOptions[i].children[j].value === id) {
                            name = this.productCateOptions[i].children[j].label;
                            return name;
                        }
                    }
                }
                return name;
            },
            uploadError(data) {
                this.$message.success(`上传失败，请重新上传`);
            },
            handleRemove(data) {
                var detailBanner = this.form.detailBanner;
                var index = detailBanner.indexOf(data.data);
                this.form.detailBanner.splice(index, 1);
            },
            uploadLogoSuccess(data) {
                if (data.returnCode == 200) {
                    this.form.listLogo = data.data;
                } else {
                    this.$message.success(`上传失败，请重新上传`);
                }
            },
            uploadSuccess(data) {
                if (data.returnCode == 200) {
                    if (this.form.detailBanner.length == 0) {
                        this.form.detailBanner = [];
                    }
                    console.log(data.data);
                    this.form.detailBanner.push(data.data);
                } else {
                    this.$message.success(`上传失败，请重新上传`);
                }
            },
            getmyHeaders() {
                var dHeader = dynamicHeader();
                this.myHeaders.signature = dHeader.signature;
                this.myHeaders.nonce = dHeader.nonce;
                this.myHeaders.timestamp = dHeader.timestamp;
                this.myHeaders.appkey = dHeader.appkey;
                this.myHeaders.token = dHeader.token;
            },
            handleBeforeUpload(file) {
                this.handleimgtype(file);
                this.getmyHeaders();
            },
            handleimgtype(file) {
                if (!(file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/jpg' || file.type === 'image/jpeg')) {
                    this.$notify.warning({
                        title: '警告',
                        message: '请上传格式为image/png, image/gif, image/jpg, image/jpeg的图片'
                    });
                    return false;
                }
                let size = file.size / 1024 / 1024 / 2;
                if (size > 2) {
                    this.$notify.warning({
                        title: '警告',
                        message: '图片大小必须小于2M'
                    });
                    return false;
                }
            },
            cancel() {
                parent.layer.close(this.windowName);
            }
        }
    };
</script>